import jwt from 'jsonwebtoken';  
const secretKey = 'qfdixon'; // 替换为你的密钥  

export const handleOrderBrocast = async (payload={},req)=>{
     console.log('handleOrderBrocast')
    const { orderId } =payload
    const orderInfo = await req.prisma.Order.findUnique({
      where: {
        id: orderId
      },
      include:{
        OrderCarTypes: true,
       }
    })
    // todo  在所有的司机当中找到现在没有订单且符合条件的司机
    const driverList = await req.prisma.User.findMany({
      where:{
        type: 'driver'
      }
    }) 
    
    const driversphones = driverList.map(item=>item.phone);
    console.log('driversphones',driversphones)

    req.ClintMap.forEach((ws,key)=>{
          const [temphone,type] = key.split('_');
          console.log('temphone',temphone)
          console.log('type',type)

          if(type === 'driver' && driversphones.includes(temphone)){
              ws.send(JSON.stringify({ type:'newOrder',payload:{ orderId } }))
          } 
    })
     

}

export const handleUpdateDriverLoc = async (payload,req)=>{
  const { orderid } = payload;
  const orderInfo = await req.prisma.Order.findUnique({
      where:{
          id: Number(orderid)
      },
      include:{
          OrderCarTypes: true,
          passenger: true
      }
  });

  const client = req.ClintMap.get(`${orderInfo.passenger.phone}_passenger`)
  if(client) {
    client.send(JSON.stringify({
        type:'updateDriveLocation',
        payload:{
          ...payload,
          destination:orderInfo.endLocation,
          origin: payload.lng+','+payload.lat
        }
    }))
    
  }

}


export const handleAappceptOrder = async (payload={},req)=>{
        
    const { orderId , token,nowLocation,fee} = payload;

    if(token){
      // token校验
      jwt.verify(token, secretKey, {
        maxAge: '1d'
      }, async (err, {user}) => {  
        console.log('err',err)
        if (!err) {

          // 司机先接单

          try{
            const preOrder = await req.prisma.Order.update({
              where:{
                id: Number(orderId),
                status: 'ordering'
              },
              data:{
                status:'willArrive',
                driverId: user.id,
                fee: Number(fee)
              }
            })
            if(!preOrder) return false;
  
            console.log('开始去处理订单流程', payload)
            if(orderId){
                const orderInfo = await req.prisma.Order.findUnique({
                    where: {
                      id: Number(orderId)
                    },
                    include:{
                      driver: true,
                      passenger: true
                     }
                })
                console.log('开始去处理订单流程',orderInfo)
                const carInfo = await req.prisma.Car.findFirst({
                  where:{
                    uid:orderInfo.driverId
                  },
                  include:{
                    brand: true
                  }
                })
                console.log('车辆信息', carInfo)
                console.log('orderInfo', orderInfo)
                const ws = req.ClintMap.get(`${orderInfo.passenger.phone}_passenger`);
                if(ws){
                    ws.send(JSON.stringify({
                        type:'driverAccpect',
                        payload: {
                            driverInfo: orderInfo.driver,
                            carInfo,
                            nowLocation,
                            startLocation: orderInfo.startLocation,
                            endLocation: orderId.endLocation
                        }
                    }))
                }
            
            }
          } catch(e) {

          }
       
        } 
      }); 
    }

  

}